package com.coderman.common.starter.excelport.imports.service.common;

import com.coderman.common.starter.excelport.imports.beans.ImportFieldBean;
import com.coderman.common.starter.excelport.imports.config.ImportBeanConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * Description: 导入转换服务
 * date: 2020/9/15 2:46 下午
 *
 * @author fanchunshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
public class ImportConvertService {
    /**
     * 执行通用转换
     * @param object
     * @param importBeanConfig
     * @throws Exception
     */
    public void exeCustomConverter(Object object, ImportBeanConfig importBeanConfig, Map<String, ImportFieldBean> importFieldBeanMap) throws Exception {
        Field[] fields = object.getClass().getDeclaredFields();
        Map<String, Map<String,Object>> metaDataMap = importBeanConfig.getMetaDataMap();

        for (int i = 0; i < fields.length; ++i) {
            Field f = fields[i];
            ImportFieldBean importFieldBean = importFieldBeanMap.get(f.getName());
            if(importFieldBean == null){
                continue;
            }
            String sourceKey = importFieldBean.getSourceKey();
            if(!StringUtils.isEmpty(sourceKey) ){
                Map<String,Object> kvMap = metaDataMap.get(sourceKey);
                Object value = ReflectionUtils.getField(f,object);
                //非空判断
                if(value == null && !importFieldBean.isNull()){
                    throw new NullPointerException("field = "+f.getName()+" value is check not null.");
                }
                int referFieldIndex = importFieldBean.getReferFieldIndex();
                //原地更改
                if (value != null && referFieldIndex < 0) {
                    Object realValue = kvMap.get(value.toString());
                    if(realValue != null){
                        ReflectionUtils.setField(f,object,realValue);
                    }else {
                        throw new NullPointerException("not found convert value,field="+f.getName());
                    }
                }
                //修改引用的属性,引用的属性不用加导入模型注解
                else if(value != null && referFieldIndex > 0) {
                    Object realValue = kvMap.get(value.toString());
                    ReflectionUtils.setField(fields[referFieldIndex],object,realValue);
                }
            }
        }
    }

}
